<template>
  <div class="zs-table-page-container">
    <div class="zs-card">
      <div class="zs-layout-flex-row zs-layout-justify-between">
        <span>
          <el-select v-model="biProjectCode" class="zs-select-md zs-space-right-sm" placeholder="项目名称"
            @change="getTableData">
            <el-option v-for="item in projectList" :key="item.biProjectCode" :label="item.projectName"
              :value="item.biProjectCode" />
          </el-select>
          <el-date-picker class="zs-select-md zs-space-right-sm" v-model="yearmonth" type="month" placeholder="月份"
            value-format="YYYY-MM" :clearable="false" @change="changePicker" />
          <el-button class="zs-btn-plain" @click="getTableData"> 查询 </el-button>
        </span>
        <span>
          <el-button class="zs-btn-md" :class="{ 'zs-btn-primary': bizSpecType == 0, 'zs-btn-info': bizSpecType == 1 }"
            @click="changeTab(0)">整场销售</el-button>
          <el-button :class="{ 'zs-btn-primary': bizSpecType == 1, 'zs-btn-info': bizSpecType == 0 }"
            @click="changeTab(1)">不含汽车+苹果</el-button>
          <el-button class="zs-btn-plain" @click="handleDownload">
            <el-icon class="el-icon--left">
              <Upload />
            </el-icon>导出
          </el-button>
        </span>
      </div>
      <div class="zs-layout-flex-col zs-layout-items-center zs-space-top-lg">

        <el-calendar class="cur-width" v-model="calendarDate" ref="calendar">
          <template #header>
            <div class="zs-title-sm zs-layout-flex-row zs-layout-justify-center zs-layout-grow"></div>
          </template>
          <template #date-cell="{ data }">
            <div class="calendar-day-box"
              :class="{ 'is-select-day': data.isSelected, 'is-weekend': [0, 6].includes(new Date(data.date).getDay()) }">
              <div>{{ `${new Date(data.day).getMonth() + 1}月${new Date(data.day).getDate()}日` }}</div>
              <div class="tag-blue" v-if="calendarList[data.day]">{{ toThousands(calendarList[data.day]) }}{{ unit
              }}</div>
            </div>
          </template>
        </el-calendar>

        <div class="cur-table cur-width zs-space-top-bg">
          <div class="cur-table-cell" v-for="(item, index) in tableHeader" :key="item">
            <div>{{ item }}</div>
            <div class="tag-blue zs-space-top-sm zs-full-item">{{ tableData[index] }}</div>
          </div>
        </div>

        <div class="zs-text-gray-dark zs-text-sm zs-space-top-bg zs-space-bottom-bg cur-width">
          *底部销售额为本月每周同一天的销售额平均值
        </div>
      </div>

    </div>

  </div>
</template>
<script setup>
import { avgSalesTotalApi, avgSalesExportApi } from "@/api/SpecialReport/index"
import dbPublicApi from '@/api/dbPublic';
// import { toThousands, dateFormat } from '@/utils/number-util'
import { toThousands } from '@/utils/number-util'
import { dateFormat } from '@/utils/number-util'
import { ref, watch } from 'vue'
import { downloadNewFile } from '@/utils/publicUtils';

const biProjectCode = ref('')
const projectList = ref([])

// 获取前一天的日期 所在的月份
var currentDate = new Date();
currentDate.setDate(currentDate.getDate() - 1);
const yearmonth = ref(dateFormat(currentDate, 'YYYY-MM'))
const curMonth = ref(currentDate.getMonth() + 1)
const calendarDate = ref(dateFormat(new Date(), 'YYYY-MM-DD'))

// 整场销售 0 不含汽车+苹果 1
const bizSpecType = ref(0)

const tableHeader = ref(['日', '一', '二', '三', '四', '五', '六'])
const tableData = ref([])
const unit = ref('')

const calendar = ref()
const calendarList = ref({})

const getList = async () => {
  // 获取 项目列表
  await dbPublicApi.queryProjectListsByPageKeyApi('page_work_order_cyhsh_sale_list').then(res => {
    if (res.data.code == 200) {
      projectList.value = res.data.data.projects;
      biProjectCode.value = res.data.data.projects[0] ? res.data.data.projects[0].biProjectCode : ''
    }
  });
};

const getTableData = () => {
  avgSalesTotalApi({ biProjectCode: biProjectCode.value, yearmonth: yearmonth.value, bizSpecType: bizSpecType.value }).then((res) => {
    if (res.data.code == 200) {
      calendarList.value = res.data.data.month
      unit.value = res.data.data.unit
      const week = res.data.data.week[0]
      tableData.value = [
        `${toThousands(week.sundayDaySales)}${unit.value}`,
        `${toThousands(week.mondayDaySales)}${unit.value}`,
        `${toThousands(week.tuesdayDaySales)}${unit.value}`,
        `${toThousands(week.wednesdayDaySales)}${unit.value}`,
        `${toThousands(week.thursdayDaySales)}${unit.value}`,
        `${toThousands(week.fridayDaySales)}${unit.value}`,
        `${toThousands(week.saturdayDaySales)}${unit.value}`,
      ]
    }
  })
}

const changePicker = () => {
  console.log(yearmonth.value)
  calendarDate.value = dateFormat(new Date(yearmonth.value), 'YYYY-MM-DD')
  getTableData()
}
const changeTab = (data) => {
  bizSpecType.value = data
  getTableData()
}

// 导出
const handleDownload = async () => {
  const fileName = `月度周平均销售额统计表.xls`;
  let fileData;
  await avgSalesExportApi({ biProjectCode: biProjectCode.value, yearmonth: yearmonth.value, bizSpecType: bizSpecType.value }).then(res => {
    fileData = res.data;
  });
  downloadNewFile(fileData, fileName);
};

watch(() => { calendarDate.value }, () => {
  const curDate = new Date(calendarDate.value)
  if (curDate.getMonth() + 1 != curMonth.value) {
    curMonth.value = curDate.getMonth() + 1
    yearmonth.value = dateFormat(curDate, 'YYYY-MM')
    getTableData()
  }
}, { deep: true });
// }, { deep: true, immediate: true });

const init = async () => {
  await getList()
  getTableData()
}
init()

</script>

<style scoped lang="scss">
.cur-width {
  width: 1140px;
}

.cur-table {
  border: 1px solid #ebeef5;
  display: flex;
  margin-left: 20px;
  margin-right: 20px;
  background-color: #f6f7fa;
}

.cur-table-cell {
  border-right: 1px solid #ebeef5;
  display: flex;
  align-items: center;
  flex-direction: column;
  flex-grow: 1;
  height: 82px;
  justify-content: center;
  padding: 0 18px;

  &:last-child {
    border-right: none;
  }
}

.tag-blue {
  min-width: 60px;
  padding: 0 10px;
  background: #ecf1fe;
  border-radius: 4px;
  color: #477afd;
  font-size: 14px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.el-calendar :deep(.el-calendar__body) {
  padding: 0;
}

.el-calendar :deep(.el-calendar__body .el-calendar-day) {
  padding: 0;
  height: 89px;
}

.el-calendar :deep(.el-calendar-table td.is-today) {
  color: #477AFD
}

.calendar-day-box {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 12px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  .day-header {
    height: 28px;
    display: flex;
    justify-content: space-between;
  }
}

.is-select-day {
  background-color: #f5f7fe !important;
}

.is-weekend {
  background-color: #F9F9F9;
}
</style>
